package com.kx.game.center.servlet;

import com.kx.game.center.bean.UserBean;
import com.kx.game.center.global.GSServices;
import com.kx.game.center.local.response.LocalErrorResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录记录
 */
@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    private static Logger logger = LoggerFactory.getLogger(LoginServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            GSServices.loadManager.redisState();
            String userId = request.getParameter("userId");
            String serverId = request.getParameter("serverId");
            String getFriendCode = request.getParameter("getFriendCode");
            UserBean userInfo = GSServices.userManager.getUserInfo(userId);
            boolean result = false;
            if (userInfo == null || userInfo.getServerId().equals(serverId)) {
                result = true;
            }
            String friendCode = "";
            if (getFriendCode.equals("1")) {
                friendCode = GSServices.loginManager.random();
                if (GSServices.userManager.existFriendCode(friendCode))
                    friendCode = "";
            }
            GSServices.localManager.sendMessage(response, result, null, friendCode);
        } catch (Exception e) {
            e.printStackTrace();
            GSServices.localManager.sendMessage(response, false, LocalErrorResponseCode.SYSTEM_ERROR, "");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
